package com.example.demo.list;

import java.util.Iterator;

/**
 * Description: 手动实现类似ArrayList<br/>
 *
 * @author liulonglong
 * @taskId <br/>
 * @Date 2020/3/13 17:29
 * @Version 1.0
 */
public class MyArrayList<T> implements Iterator<T> {

    private static final int DEFAULT_CAPACITY = 10;

    private int capacity;

    private int size;

    private T[] items;

    public MyArrayList() {
        doClear();
    }

    private void doClear() {
        size = 0;
        ensureCapacity(DEFAULT_CAPACITY);
    }

    private void ensureCapacity(int newCapacity) {
        if (size() > newCapacity) {
            return;
        }
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size() == 0;
    }

    public void trimToSize() {
        ensureCapacity(size());
    }

    public T get(int index) {
        if (index < 0 || index > size() - 1) {
            throw new ArrayIndexOutOfBoundsException("idx is illeagal!");
        }
        return items[index];
    }

    public T set(int idx, T t) {
        if (idx < 0 || idx > size() - 1) {
            throw new ArrayIndexOutOfBoundsException("idx is illeagal!");
        }
        T oldVal = items[idx];
        items[idx] = t;
        return oldVal;
    }

    @Override public boolean hasNext() {
        return false;
    }

    @Override public T next() {
        return null;
    }
}
